package com.qs.worklog.servlet;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.qs.worklog.common.CommonDate;
import com.qs.worklog.dao.TaskDAO;
import com.qs.worklog.dao.UserDAO;
import com.qs.worklog.dao.impl.ImplTaskDAO;
import com.qs.worklog.dao.impl.ImplUserDAO;
import com.qs.worklog.entity.Task;
import com.qs.worklog.entity.User;


public class TaskJobServlet extends HttpServlet implements Serializable {
	private static final long serialVersionUID = 1L;

	public TaskJobServlet (){
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		String uri = request.getRequestURI();
		String path = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));		
		try{
			if("/register".equalsIgnoreCase(path)){
				this.register(request,response);
			}else if("/getTask".equalsIgnoreCase(path)){
				this.query(request,response);
			}else if("/save".equalsIgnoreCase(path)){
				this.save(request, response);
			}else if("/delete".equalsIgnoreCase(path)){
				this.delete(request, response);
			}else if("/report".equalsIgnoreCase(path)){
				this.report(request, response);
			}else if("/query".equalsIgnoreCase(path)){
				this.query(request, response);
			}else if("/home".equalsIgnoreCase(path)){
				this.home(request, response);
			}else if("/export".equalsIgnoreCase(path)){
				this.export(request, response);
			}else{
				throw new Exception("Unsupported service");
			}
		}catch(Exception e){
			throw new ServletException(e);
		}
	}
	
	private void home(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		UserDAO userDao = new ImplUserDAO();
		List<User> users = userDao.findAllUser();
		request.setAttribute("users", users);
		request.getRequestDispatcher("operator.jsp").forward(request, response);
	}
	
	private void query(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String userId = request.getParameter("userId");
		String startTimeStr = request.getParameter("startTime");
		String endTimeStr = request.getParameter("endTime");
		String actionTime = request.getParameter("actionTime");
		int uid = Integer.parseInt(userId);
		List<Task> tasks = null;
		TaskDAO taskDao = new ImplTaskDAO();
		Date startDate = null, endDate = null;
		try{
			if(actionTime == null){
				startDate = CommonDate.parseDate(startTimeStr, CommonDate.SHORT);
				endDate = CommonDate.parseDate(endTimeStr, CommonDate.SHORT);
			}else{
				startDate = CommonDate.parseDate(actionTime, CommonDate.SHORT);
				endDate = startDate;
			}
		}catch(Exception e){}
		tasks = taskDao.findTasks(uid, startDate, endDate);
		JSONArray tasksJson = new JSONArray();		
		for(Task task : tasks){
			JSONObject taskObj = new JSONObject();
			taskObj.put("id", task.getId());
			taskObj.put("uid", task.getUid());
			taskObj.put("userName", task.getUserName());
			taskObj.put("actionTime", task.getActionTime());
			taskObj.put("timeCost", task.getTimeCost());
			taskObj.put("description", task.getDescription());
			tasksJson.put(taskObj);
		}
		String result = tasksJson.toString();
		writeData(response, result.getBytes());
	}
	
	private void report(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		UserDAO userDao = new ImplUserDAO();
		List<User> users = userDao.findAllUser();
		request.setAttribute("users", users);
		request.setAttribute("currentDate", CommonDate.getInstance(CommonDate.SHORT).toString());
		request.getRequestDispatcher("report.jsp").forward(request, response);
	}
	
	private void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String userId = request.getParameter("userId");
		String startTimeStr = request.getParameter("startTime");
		String endTimeStr = request.getParameter("endTime");
		String actionTime = request.getParameter("actionTime");
		int uid = Integer.parseInt(userId);
		List<Task> tasks = null;
		TaskDAO taskDao = new ImplTaskDAO();
		Date startDate = null, endDate = null;
		try{
			if(actionTime == null){
				startDate = CommonDate.parseDate(startTimeStr, CommonDate.SHORT);
				endDate = CommonDate.parseDate(endTimeStr, CommonDate.SHORT);
			}else{
				startDate = CommonDate.parseDate(actionTime, CommonDate.SHORT);
				endDate = startDate;
			}
		}catch(Exception e){}
		tasks = taskDao.findTasks(uid, startDate, endDate);
		uid = -1;
		String itemDate = "";
		StringBuffer report = new StringBuffer();
		int count = 0;
		for(Task task : tasks){
			count ++;
			actionTime = CommonDate.getInstance(task.getActionTime(), CommonDate.SHORT).toString();
			if(!actionTime.equals(itemDate)){
				if(!"".equals(itemDate)){
					report.append("\n");
				}
				itemDate = actionTime;
				uid = -1;
				report.append(actionTime + ":\n");
				count = 1;
			}
			if(uid != task.getUid()){
				uid = task.getUid();
				report.append("\t"+task.getUserName() + ":\n");
				count = 1;
			}
			report.append("\t    "+count + ". " + task.getDescription() + "\n");
		}
		writeData(response, report.toString().getBytes());
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String id = request.getParameter("id");
		int tid = Integer.parseInt(id);
		TaskDAO taskDao = new ImplTaskDAO();
		String result = "";
		try{
			taskDao.deleteByTid(tid);
			result = "success";
		}catch(Exception e){
			result = "fail";
		}
		writeData(response, result.getBytes());
	}
	
	private void save(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException, ServletException{
		String[] id = request.getParameterValues("id");
		String[] description = request.getParameterValues("description");
		String[] timeCost = request.getParameterValues("timeCost");
		String date = request.getParameter("actionDate");
		String userId = request.getParameter("userId");
		if(date == null){
			throw new ServletException("Action date cannot be empty");
		}
		try{
			Date saveDate = CommonDate.parseDate(date, CommonDate.SHORT);
			TaskDAO taskDao = new ImplTaskDAO();
			for(int i = 0; i < description.length; i++){
				Task task = new Task();
				task.setDescription(description[i]);
				task.setActionTime(new java.sql.Date(saveDate.getTime()));
				task.setTimeCost(Double.parseDouble(timeCost[i]));
				task.setUid(Integer.parseInt(userId));
				if(id[i].equals("")){
					task.setId(-1);
				}else{
					task.setId(Integer.parseInt(id[i]));
				}
				taskDao.saveTask(task);
			}
		}catch(Exception e){
			e.printStackTrace();
			String msg = "Failed:" + e.getMessage();
			writeData(response, msg.getBytes());
			return;
		}
		writeData(response, "SUCCESS".getBytes());
	}
	
	private static void writeData(HttpServletResponse response, byte[] data) throws IOException{
		ServletOutputStream responseOutputStream = response.getOutputStream();
		responseOutputStream.write(data);
		responseOutputStream.flush();
		responseOutputStream.close();
	}
	
	private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String name = (request.getParameter("name")).trim();
		UserDAO userDao = new ImplUserDAO();
		User user = userDao.findUserByName(name);
		if(user != null){
			request.setAttribute("registerMsg", "User ["+name+"] already exists");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}else{
			user = new User();
			user.setName(name);
			userDao.saveUser(user);
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}
}
